package com.lockapp;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.lockapp.adapter.ListaAplicativosAdapter;
import com.lockapp.adapter.ListaAplicativosBloqueadosAdapter;
import com.lockapp.database.BlockCursor;
import com.lockapp.database.BlockDAO;
import com.lockapp.database.SenhaCursor;
import com.lockapp.database.SenhaDAO;
import com.lockapp.entity.Block;
import com.lockapp.services.LockService;

public class PrincipalActivity extends FragmentActivity {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;
	
	private static List<Block> listaAplicativos;
	private static PackageManager pm;
	
	private static BlockDAO dao;
	private static BlockCursor cursor;
	private static List<Block> listaAplicativosBloqueados;
	
	private SenhaDAO senhaDao;
	private SenhaCursor senhaCursor;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//verificando se tem uma senha registrada, caso não, abre a atividade para adicionar uma senha
		senhaDao = new SenhaDAO(this);
		senhaCursor = senhaDao.getSenhas();
		if(senhaCursor == null || senhaCursor.getCount() == 0){
			startActivity(new Intent(this, DefinirSenhaActivity.class));
			finish();
		}
		
		setContentView(R.layout.layout_principal);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		listaAplicativos = new ArrayList<Block>();
		pm = getPackageManager();
		List<PackageInfo> listApps = pm.getInstalledPackages(0);
		for(PackageInfo info : listApps){
//			if(!isSystemPackage(info)){
				Block app = new Block();
				app.setNomeApp(info.applicationInfo.loadLabel(getPackageManager()).toString());
				app.setPacoteApp(info.packageName);
				app.setIconeApp(info.applicationInfo.loadIcon(getPackageManager()));
				listaAplicativos.add(app);
//			}
		}
		
		
		dao = new BlockDAO(this);
		//lista dos apps bloqueados
		listaAplicativosBloqueados = new ArrayList<Block>();
		carregaAppsBloqueados();
		dao.close();
		cursor.close();
		
		startService(new Intent(this, LockService.class));
		
	}
	
	public static void carregaAppsBloqueados(){
		listaAplicativosBloqueados.clear();
		cursor = dao.getAll();
		for(int i = 0; i < cursor.getCount(); i++){
			cursor.moveToPosition(i);
			Block block = new Block();
			block.setNomeApp(cursor.getNomeApp());
			block.setPacoteApp(cursor.getPacoteApp());
			block.setIconeApp(getDrawableFromBytes(cursor.getImagemApp()));
			listaAplicativosBloqueados.add(block);
		}
	}
	
	//método para transformar byte[] em Drawable
	public static Drawable getDrawableFromBytes(byte[] imageBytes) {
		if (imageBytes != null)
			return new BitmapDrawable(BitmapFactory.decodeByteArray(imageBytes,0, imageBytes.length));
		else
			return null;
	 }
	
//	private boolean isSystemPackage(PackageInfo pkgInfo) {
////	    return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true : false;
//	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_principal, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuListaMensagens:
			startActivity(new Intent(this, ListaMensagemActivity.class));
			overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a DummySectionFragment (defined as a static inner class
			// below) with the page number as its lone argument.
			Fragment fragment = new DummySectionFragment();
			Bundle args = new Bundle();
			args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount() {
			return 2;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase();
			case 1:
				return getString(R.string.title_section2).toUpperCase();
			}
			return null;
		}
	}

	/**
	 * A dummy fragment representing a section of the app, but that simply
	 * displays dummy text.
	 */
	public static class DummySectionFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";

		public DummySectionFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = null;
			if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
				view = inflater.inflate(R.layout.layout_lista_bloqueados, null);
				ListView listViewAppsBloqueados = (ListView) view.findViewById(R.id.listViewBloqueados);
				
				//inseri codigo
				carregaAppsBloqueados();
				ListaAplicativosBloqueadosAdapter adapter = new ListaAplicativosBloqueadosAdapter(getActivity(), listaAplicativosBloqueados);
				listViewAppsBloqueados.setAdapter(adapter);
			}
			if(getArguments().getInt(ARG_SECTION_NUMBER) == 2){
				view = inflater.inflate(R.layout.layout_lista_apps, null);
				ListView listViewApps = (ListView) view.findViewById(R.id.listViewApps);
				ListaAplicativosAdapter adapter = new ListaAplicativosAdapter(getActivity(), listaAplicativos);
				listViewApps.setAdapter(adapter);
				listViewApps.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> adapterView, View v, int position, long longId) {
						Block block = listaAplicativos.get(position);
						//transformando o drawable (imagem do aplicativo) em byte[], para salvar no banco
						Bitmap bitmap = ((BitmapDrawable)block.getIconeApp()).getBitmap();
						ByteArrayOutputStream stream = new ByteArrayOutputStream();
						bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
						byte[] bitmapdata = stream.toByteArray();
						block.setArrayImg(bitmapdata);
						block.setLiberacao(0);
						dao.inserir(block);
						
					}
				});
			}
			
			return view;
		}
	}

}
